package tech.shupi.babytapmobile

import android.content.Intent
import android.util.Log
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import tech.shupi.babytapmobile.util.CardHttpClient
import tech.shupi.babytapmobile.service.GolangApiService
import android.content.Context
import android.os.Build

class CardApiModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    companion object {
        private const val TAG = "CardApiModule"
    }
    
    private val mHttpClient = CardHttpClient()
    
    init {
        Log.i(TAG, "CardApiModule 初始化完成")
    }
    
    override fun getName(): String = "CardApiModule"
    
    @ReactMethod
    fun startApiServer(promise: Promise) {
        try {
            Log.i(TAG, "启动 Golang API 服务器...")
            
            val intent = Intent(reactApplicationContext, GolangApiService::class.java).apply {
                action = "START_API"
            }
            
            // 启动前台服务
            reactApplicationContext.startForegroundService(intent)
            
            // 等待服务启动和服务器初始化
            Log.i(TAG, "等待服务启动...")
            Thread.sleep(3000) // 增加等待时间到3秒
            
            // 尝试绑定服务来获取状态
            var boundService: GolangApiService? = null
            try {
                val connection = object : android.content.ServiceConnection {
                    override fun onServiceConnected(name: android.content.ComponentName?, binder: android.os.IBinder?) {
                        boundService = (binder as? GolangApiService.LocalBinder)?.getService()
                        Log.i(TAG, "✅ 服务绑定成功")
                    }
                    
                    override fun onServiceDisconnected(name: android.content.ComponentName?) {
                        boundService = null
                        Log.w(TAG, "服务连接断开")
                    }
                }
                
                val bound = reactApplicationContext.bindService(intent, connection, Context.BIND_AUTO_CREATE)
                if (bound) {
                    Log.i(TAG, "服务绑定请求成功")
                }
                
                // 等待服务绑定完成
                Thread.sleep(1000)
                
                // 获取实际端口并更新 HTTP 客户端
                val currentService = boundService
                if (currentService != null) {
                    val actualPort = currentService.getServerPort()
                    mHttpClient.setPort(actualPort)
                    Log.i(TAG, "✅ 更新 HTTP 客户端端口: $actualPort")
                    
                    // 检查服务器是否正在运行
                    if (currentService.isServerRunning()) {
                        Log.i(TAG, "✅ 服务器正在运行")
                    } else {
                        Log.w(TAG, "⚠️ 服务器可能未完全启动")
                    }
                } else {
                    Log.w(TAG, "无法获取服务实例，使用默认端口")
                    mHttpClient.setPort(8553) // 使用默认端口
                }
                
                // 解绑服务
                reactApplicationContext.unbindService(connection)
                
            } catch (e: Exception) {
                Log.w(TAG, "服务绑定失败，使用默认端口", e)
                mHttpClient.setPort(8553) // 使用默认端口
            }
            
            // 启动成功后，设置设备名称为手机型号
            try {
                val manufacturer = Build.MANUFACTURER
                val model = Build.MODEL
                val deviceName = "$manufacturer $model"
                
                Log.i(TAG, "设置设备名称为: $deviceName")
                val setDeviceResponse = mHttpClient.setDeviceName(deviceName)
                Log.i(TAG, "✅ 设备名称设置成功: $setDeviceResponse")
            } catch (e: Exception) {
                Log.w(TAG, "设置设备名称失败，使用默认名称", e)
            }
            
            promise.resolve(true)
            Log.i(TAG, "✅ Golang API 服务器启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动 Golang API 服务器失败", e)
            promise.reject("API_SERVER_ERROR", "启动 Golang API 服务器失败: ${e.message}", e)
        }
    }
    
    @ReactMethod
    fun getCards(promise: Promise) {
        try {
            Log.d(TAG, "开始获取卡片列表...")
            val response = mHttpClient.getCards()
            Log.i(TAG, "卡片列表获取成功")
            promise.resolve(response)
        } catch (e: Exception) {
            Log.e(TAG, "获取卡片列表失败", e)
            promise.reject("API_ERROR", "获取卡片列表失败: ${e.message}", e)
        }
    }
    
    @ReactMethod
    fun createCard(cardJson: String, promise: Promise) {
        try {
            Log.d(TAG, "开始创建卡片...")
            val response = mHttpClient.createCard(cardJson)
            Log.i(TAG, "卡片创建成功")
            promise.resolve(response)
        } catch (e: Exception) {
            Log.e(TAG, "创建卡片失败", e)
            promise.reject("API_ERROR", "创建卡片失败: ${e.message}", e)
        }
    }
    
    @ReactMethod
    fun updateCard(id: Int, cardJson: String, promise: Promise) {
        try {
            Log.d(TAG, "开始更新卡片... id=$id")
            val response = mHttpClient.updateCard(id, cardJson)
            Log.i(TAG, "卡片更新成功")
            promise.resolve(response)
        } catch (e: Exception) {
            Log.e(TAG, "更新卡片失败", e)
            promise.reject("API_ERROR", "更新卡片失败: ${e.message}", e)
        }
    }
    
    @ReactMethod
    fun deleteCard(id: Int, promise: Promise) {
        try {
            Log.d(TAG, "开始删除卡片... id=$id")
            val response = mHttpClient.deleteCard(id)
            Log.i(TAG, "卡片删除成功")
            promise.resolve(response)
        } catch (e: Exception) {
            Log.e(TAG, "删除卡片失败", e)
            promise.reject("API_ERROR", "删除卡片失败: ${e.message}", e)
        }
    }

    @ReactMethod
    fun getLocalIPAddress(promise: Promise) {
        try {
            // 使用更现代的方法获取网络接口信息
            val networkInterfaces = java.net.NetworkInterface.getNetworkInterfaces()
            while (networkInterfaces.hasMoreElements()) {
                val networkInterface = networkInterfaces.nextElement()
                
                // 跳过回环接口和未启用的接口
                if (networkInterface.isLoopback || !networkInterface.isUp) {
                    continue
                }
                
                val inetAddresses = networkInterface.inetAddresses
                while (inetAddresses.hasMoreElements()) {
                    val inetAddress = inetAddresses.nextElement()
                    
                    // 只处理 IPv4 地址
                    if (inetAddress is java.net.Inet4Address) {
                        val ip = inetAddress.hostAddress
                        
                        // 检查是否是局域网 IP
                        if (ip != null && (ip.startsWith("192.168.") || 
                            ip.startsWith("10.") || 
                            ip.startsWith("172."))) {
                            Log.i(TAG, "获取到局域网 IP 地址: $ip")
                            promise.resolve(ip)
                            return
                        }
                    }
                }
            }
            
            // 如果没有找到局域网 IP，尝试获取 WiFi IP
            try {
                val wifiManager = reactApplicationContext.getSystemService(Context.WIFI_SERVICE) as android.net.wifi.WifiManager
                val wifiInfo = wifiManager.connectionInfo
                
                if (wifiInfo != null && wifiInfo.ipAddress != 0) {
                    val ipAddress = android.text.format.Formatter.formatIpAddress(wifiInfo.ipAddress)
                    Log.i(TAG, "获取到 WiFi IP 地址: $ipAddress")
                    promise.resolve(ipAddress)
                    return
                }
            } catch (e: Exception) {
                Log.w(TAG, "获取 WiFi IP 失败，尝试其他方法", e)
            }
            
            // 如果都没有找到，返回本地地址
            Log.w(TAG, "未找到局域网 IP，使用本地地址")
            promise.resolve("127.0.0.1")
            
        } catch (e: Exception) {
            Log.e(TAG, "获取局域网 IP 失败", e)
            promise.reject("IP_ERROR", "获取局域网 IP 失败: ${e.message}", e)
        }
    }

    @ReactMethod
    fun getImageData(imagePath: String, promise: Promise) {
        try {
            Log.d(TAG, "开始获取图片数据... path=$imagePath")
            
            // 构建完整的文件路径（使用外部存储）
            val fullPath = "${reactApplicationContext.getExternalFilesDir(null)}/golang_data/$imagePath"
            val file = java.io.File(fullPath)
            
            if (!file.exists()) {
                Log.w(TAG, "图片文件不存在: $fullPath")
                promise.reject("FILE_NOT_FOUND", "图片文件不存在: $imagePath")
                return
            }
            
            // 读取文件数据
            val inputStream = java.io.FileInputStream(file)
            val bytes = inputStream.readBytes()
            inputStream.close()
            
            // 转换为 Base64 字符串
            val base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
            
            // 获取 MIME 类型
            val mimeType = when {
                imagePath.endsWith(".jpg", true) || imagePath.endsWith(".jpeg", true) -> "image/jpeg"
                imagePath.endsWith(".png", true) -> "image/png"
                imagePath.endsWith(".gif", true) -> "image/gif"
                imagePath.endsWith(".webp", true) -> "image/webp"
                else -> "application/octet-stream"
            }
            
            // 使用 WritableMap 构建响应数据
            val response = com.facebook.react.bridge.Arguments.createMap().apply {
                putString("data", "data:$mimeType;base64,$base64")
                putInt("size", bytes.size)
                putString("mimeType", mimeType)
            }
            
            Log.i(TAG, "图片数据获取成功: $imagePath, 大小: ${bytes.size}")
            promise.resolve(response)
            
        } catch (e: Exception) {
            Log.e(TAG, "获取图片数据失败", e)
            promise.reject("IMAGE_ERROR", "获取图片数据失败: ${e.message}", e)
        }
    }

    @ReactMethod
    fun sendUDPBroadcast(promise: Promise) {
        try {
            Log.i(TAG, "开始通过 Golang 发送 UDP 广播...")
            
            // 通过 Golang 服务发送 UDP 广播
            val response = mHttpClient.sendUDPBroadcast()
            Log.i(TAG, "✅ Golang UDP 广播发送成功")
            promise.resolve(response)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 通过 Golang 发送 UDP 广播失败", e)
            promise.reject("UDP_BROADCAST_ERROR", "发送UDP广播失败: ${e.message}", e)
        }
    }

    @ReactMethod
    fun getDeviceModel(promise: Promise) {
        try {
            val manufacturer = Build.MANUFACTURER
            val model = Build.MODEL
            val deviceName = "$manufacturer $model"
            
            Log.i(TAG, "获取设备型号: $deviceName")
            promise.resolve(deviceName)
            
        } catch (e: Exception) {
            Log.e(TAG, "获取设备型号失败", e)
            promise.reject("DEVICE_MODEL_ERROR", "获取设备型号失败: ${e.message}", e)
        }
    }

    @ReactMethod
    fun getDeviceName(promise: Promise) {
        try {
            Log.i(TAG, "获取设备名称...")
            val response = mHttpClient.getDeviceName()
            Log.i(TAG, "✅ 获取设备名称成功")
            promise.resolve(response)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取设备名称失败", e)
            promise.reject("DEVICE_NAME_ERROR", "获取设备名称失败: ${e.message}", e)
        }
    }

    @ReactMethod
    fun setDeviceName(name: String, promise: Promise) {
        try {
            Log.i(TAG, "设置设备名称: $name")
            val response = mHttpClient.setDeviceName(name)
            Log.i(TAG, "✅ 设置设备名称成功")
            promise.resolve(response)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 设置设备名称失败", e)
            promise.reject("SET_DEVICE_NAME_ERROR", "设置设备名称失败: ${e.message}", e)
        }
    }
} 